package com.example.goods_manage.exception;

import com.example.goods_manage.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Component
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 参数校验不通过
     *
     * @param e BindException
     * @return AjaxResult
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handlerBindException(BindException e) {
        return AjaxResult.error(this.buildMsg(e.getBindingResult()));
    }

    /**
     * 参数校验不通过
     *
     * @param e MethodArgumentNotValidException
     * @return AjaxResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return AjaxResult.error(this.buildMsg(e.getBindingResult()));
    }

    /**
     * Exception
     * 对于没有指定处理的异常，需要捕获一个最大的Exception
     * 否则会发起二次请求，和 LoginInterceptor 起冲突
     *
     * @param e Exception
     * @return AjaxResult
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handlerException(Exception e) {
        LOGGER.error("未处理异常", e);
        return AjaxResult.error("系统错误");
    }


    /**
     * 构建参数错误提示信息
     *
     * @param bindingResult BindingResult
     * @return String
     */
    private String buildMsg(BindingResult bindingResult) {
        StringBuilder builder = new StringBuilder(32);
        for (FieldError error : bindingResult.getFieldErrors()) {
            builder.append(", [").append(error.getField()).append(":").append(error.getDefaultMessage()).append("]");
        }
        return builder.substring(2);
    }

}
